package com.jackfangqi.zhihuijizhou.utils;

import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Set;
import java.util.zip.GZIPInputStream;

/**
 * Created by gggcccwww on 2015/6/2.
 */


public final class CommonHttpUtil {

    public static final int TIMEOUT_CONNECT =5000;//默认的连接超时时间
    public static byte[] doGet(String url){
        return doGet(url,null);
    }

    /**
     * 实现GET请求，并可以设置网络的请求头
     */
    public static byte[] doGet(String url,HashMap<String,String> headers){
        byte[] ret=null;
        if (url != null) {
            try {
                URL u = new URL(url);
                HttpURLConnection huc = (HttpURLConnection) u.openConnection();
                //1.设置请求方法
                huc.setRequestMethod("GET");
                //2.close 每次连接创建新的socket keep-alive 每次尝试重用原来的socket
                huc.setRequestProperty("Connection","keep-alive");
                //3.可以根据这个判断设备的系统
                huc.setRequestProperty("User-Agent","CommonHttpUtil/0.1[Android]");
                //TODO 进行附加HTTP头字段的设置
                if (headers != null) {
                    Set<String> keySet = headers.keySet();
                    for(String key:keySet){
                        String value = headers.get(key);
                        huc.setRequestProperty(key,value);
                    }
                }
                //TODO 进行连接操作
                huc.setConnectTimeout(TIMEOUT_CONNECT);
                //允许连接自动的处理网络重定向
                huc.setInstanceFollowRedirects(true);
                //设置客户端与服务器接收数据时总共允许接收多长时间，超过抛异常
//                huc.setReadTimeout();
                huc.connect();//连接
                int responseCode = huc.getResponseCode();//返回服务器状态码
//                if (responseCode == 200) {//即使不是200也会有数据流
//                    InputStream inputStream = huc.getInputStream();
//                    //网络数据可能是经过压缩的，需要检查
//                    String contentEncoding = huc.getContentEncoding();//如果有值，进行解压缩
//                    if (contentEncoding != null) {
//                        if(contentEncoding.equals("gzip")){
//                            //对应Content-Encoding:gzip
//                            inputStream=new GZIPInputStream(inputStream);
//                        }else{
//                            //TODO 处理非gzip的压缩方式
//                        }
//                    }
//                    ret=StreamUtil.readStream(inputStream);
//                    inputStream.close();
//                }else{}
                InputStream inputStream = huc.getInputStream();
                if(inputStream!=null){
                    Log.d("------>","呵呵");
                }else{
                    Log.d("------>","不科学");
                }
                ret=StreamUtil.readStream(inputStream);
                huc.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 传递key=value&key=value的数据请求
     * @param url
     * @param params
     * @param headers
     * @return
     */
    public static byte[] doPost(String url,HashMap<String,String> params,HashMap<String,String> headers){
        byte[] ret=null;
        if (url != null) {
            try {
                URL u = new URL(url);
                HttpURLConnection huc = (HttpURLConnection) u.openConnection();
                //POST请求的数据设置部分
                huc.setDoInput(true);
                if(params!=null){
                    if(!params.isEmpty()){
                        //设置开启数据输出
                        huc.setDoOutput(true);
                    }
                }
                //1.连接方式
                huc.setRequestMethod("POST");
                huc.setRequestProperty("Connection", "Keep-Alive");
                huc.setRequestProperty("Charset", "UTF-8");
//                huc.setRequestProperty("User-Agent","CommonHttpUtil/0.1[Android]");
                //3.设置附加HTTP头字段
                //TODO 当进行POST请求时，必须设置Content-Type字段，只有设置该字段，服务器才能够正确获取参数
                huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//提交服务器key=value方法的参数就是这种类型
                if(headers!=null){
                    Set<String> keySet = headers.keySet();
                    for(String key:keySet){
                        String value = headers.get(key);
                        huc.setRequestProperty(key,value);
                    }
                }


                if(params!=null && !params.isEmpty()){
                    //user=admin&pass=123
                    StringBuilder sb=new StringBuilder();
                    Set<String> keyset = params.keySet();
                    //处理请求参数
                    for(String key:keyset){
                        String value = params.get(key);
                        sb.append(URLEncoder.encode(key,"UTF-8"));
                        sb.append('=');
                        sb.append(URLEncoder.encode(value, "UTF-8"));
                        sb.append('&');
                    }
//                    sb.deleteCharAt(sb.length()-1);//去掉最后一个&
                    String requestStr = sb.toString();
                    Log.d("---->",requestStr);
                    byte[] data=requestStr.getBytes();
                    int length = data.length;
                    Log.d("------>",String.valueOf(length));

                    //获取长度，设置请求头，Content-Length代表提交的内容长度
//                    huc.setRequestProperty("Content-Length",Integer.toString(data.length));
                    huc.setRequestProperty("Content-Length",String.valueOf(length));
                    //输出数据
                    huc.connect();
                    OutputStream outputStream = huc.getOutputStream();
                    outputStream.write(data);
                    outputStream.flush();
                    outputStream.close();
                }
                int responseCode = huc.getResponseCode();
                //可以不用判断，其他码也会有数据
                InputStream inputStream = huc.getInputStream();
                if (inputStream != null) {
                    //TODO 处理压缩的情况
                    String contentEncoding = huc.getContentEncoding();
                    if ("gzip".equals(contentEncoding)) {
                        inputStream = new GZIPInputStream(inputStream);

                    }
                    ret=StreamUtil.readStream(inputStream);
                    inputStream.close();
                }
                huc.disconnect();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }
}
